package 多线程和队列.多任务执行.Fututre;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @author Amos  2022/12/4
 */
public class FutureAsyncDemo {

    static Random random = new Random();
    static ExecutorService executor =
            Executors.newCachedThreadPool();

    //接收文章名称，获取并计算文章分数
    public static int getArticleScore(String name) {
        Future<Integer> futureA =
                executor.submit(new
                        CalculateArticleScoreA());
        Future<Integer> futureB =
                executor.submit(new
                        CalculateArticleScoreA());
        Future<Integer> futureC =
                executor.submit(new
                        CalculateArticleScoreA());
        doSomeThingElse();
        Integer a = null;
        try {
            a = futureA.get();
        } catch (InterruptedException | ExecutionException e) {
            futureA.cancel(true);
            e.printStackTrace();
        }
        Integer b = null;
        try {
            b = futureB.get();
        } catch (InterruptedException | ExecutionException e) {
            futureB.cancel(true);
            e.printStackTrace();
        }
        Integer c = null;
        try {
            c = futureC.get();
        } catch (InterruptedException | ExecutionException e) {
            futureC.cancel(true);
            e.printStackTrace();
        }
        executor.shutdown();
        return a + b + c;
    }

    private static void doSomeThingElse() {
        System.out.println("exec other things");
    }

    public static void main(String[] args) {
        System.out.println(getArticleScore("demo"))
        ;
    }
}

class CalculateArticleScoreA implements
        Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        //业务代码
        Random random = new Random();
        TimeUnit.SECONDS.sleep(3);
        System.out.println(Thread.currentThread().getName());
        return random.nextInt(100);
    }
}
